using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ShootTower : TowerHolder
{   public static ShootTower shootTower;
    public GameObject arrow;
    [Header("基本参数")]
    public float arrowSpeed;
    public float attackCounter;
    public float attackNextTime;
    public LayerMask targetLayer;
    public float radius = 10f;
    public List<Transform> enemyList = new List<Transform>();


    private void Awake() {
        shootTower = this;
    }
    
    public override void Update() {
        CollectEnemy();
        if(enemyList != null){
            AttackEnemy();
            for (int i = 0; i < enemyList.Count; i++){//清除被消灭的敌人
                if(enemyList[i] == null){
                    enemyList.Remove(enemyList[i]);
                }
            }
        }

    }
    public void OnDrawAttackRange(){
        Gizmos.color = Color.blue;
        Gizmos.DrawWireSphere(transform.position , radius);
    }

    public void CollectEnemy(){//收集敌人进入列表
        Collider2D[] enemies = Physics2D.OverlapCircleAll(transform.position , radius, targetLayer);
        foreach (var item in enemies)
        {
            if(!enemyList.Contains(item.transform)){
                enemyList.Add(item.transform);
            }
            for(int i = 0; i < enemyList.Count; i++){
                if(enemyList[i] == null){
                    enemyList.Remove(enemyList[i]);
                }
            }
        }

        
    }
    public void AttackEnemy(){//生成飞剑攻击
        if(enemyList.Count > 0){
            attackCounter -= Time.deltaTime;
            if(attackCounter <= 0){
                attackCounter = attackNextTime;
                FlyToEnemy();
                Instantiate(arrow , transform.position , arrow.transform.rotation);
            }
        }
    }
    public void FlyToEnemy(){//判断敌人方向
        if(enemyList.Count > 0){
            Vector3 direction =enemyList[0].position - transform.position;
            float angle = Mathf.Atan2(direction.x , direction.y) * Mathf.Rad2Deg;
            arrow.transform.rotation = Quaternion.AngleAxis(-angle , Vector3.forward);
        }
    }
}
